import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './order.scss'


import { set as setGlobalData, get as getGlobalData } from '../../static/js/global_data'
import api from '../../service/api'
import common from '../../service/common'
import base from '../../static/js/base'

import TabBar from '../../components/order/tabBar'
import Goodlist from '../../components/order/goodlist'
import Btngroups from '../../components/order/btngroups'

export default class Index extends Component {
    config = {
        navigationBarTitleText: '订单',
        onReachBottomDistance: 1
    }
    constructor() {
        super(...arguments)
        this.state = {
            pagesize: getGlobalData('pagesize'),
            pageindex: 1,
            hasPgEnd: false,
            showView: false,
            domainImg: getGlobalData('domainImg'),
            tab: [
                {'txt': '全部','state': '0'},
                {'txt': '待付款','state': '1'},
                {'txt': '待发货','state': '2'},
                {'txt': '待收货','state': '3'},
                {'txt': '待自提','state': '5'},
                {'txt': '已完成','state': '4'},
                {'txt': '售后','state': '6'}
            ], //订单头部tab
            orderlist: []
        }
    }
    componentWillMount() {
        console.log(this.$router.params)
        base.showLoading()
        this.state.states =  this.$router.params.stateId
        this.getOrderList()
        this.setState({ 
            states: this.$router.params.stateId,
            scrollIntoView: 'tab' + this.$router.params.stateId
         })
    }
    // 点击tab切换
    tabTap(id) {
        this.setState({
            states: id,
            orderlist: [],
            pageindex: 1,
            hasPgEnd: false,
            showView: false
        }, () => {
            base.showLoading()
            this.getOrderList()
        })
    }
    // 获取订单列表
    getOrderList() {
        const str = `mebNo&ShopNo&state&pagesize&pageindex`
        // const params = {
        //     bNo: 404,
        //     mebno: getGlobalData('C_MB_NO'),
        //     pagesize: this.state.pagesize,
        //     pageindex: this.state.pageindex,
        //     state: this.state.states,
        //     ShopNo: getGlobalData('SHOP_NO')
        // }
        const params = {
            bNo: 'GO0101',
            mebNo: 1009047,//getGlobalData('C_MB_NO'),
            ShopNo: 100233,//getGlobalData('SHOP_NO'),
            state: 1,//this.state.states,
            pagesize: 1,//this.state.pagesize,
            pageindex: 10//this.state.pageindex
        }
         let orderlists = []
        api.get(str, params, (res) => {
            if(res.code === 0){
                if (!res.data.rows) {
                    this.state.hasPgEnd = true
                } else {
                    if (res.data.rows.length < this.state.pagesize) {
                        this.state.hasPgEnd = true
                    }
                    res.data.rows.map((item, i) => {
                        item.totalMoney = item.totalMoney.toFixed(2);//总计
                        item.orderTime = item.orderTime.substring(0,10)+" "+item.orderTime.substring(11,item.orderTime.length)
                    })
                }
                if (this.state.pageindex == 1) {
                    orderlists = res.data.rows || []
                } else {
                    orderlists = this.state.orderlist.concat(orderlists)
                }
                this.setState({
                    orderlist: orderlists,
                    hasPgEnd: this.state.hasPgEnd,
                    showView: true
                })
            }
        }, (res) => {
            console.log(res)
            if (!res.orderlist) {
                this.state.hasPgEnd = true
            } else {
                if (res.orderlist.length < this.state.pagesize) {
                    this.state.hasPgEnd = true
                }
                res.orderlist.map((item, i) => {
                    item.n_allmoney = item.n_allmoney.toFixed(2)
                })
            }
            if (this.state.pageindex == 1) {
                orderlists = res.orderlist || []
            } else {
                orderlists = this.state.orderlist.concat(orderlists)
            }
            this.setState({
                orderlist: orderlists,
                hasPgEnd: this.state.hasPgEnd,
                showView: true
            })
        }, (com) => {
            Taro.hideLoading()
        })
    }
    // 点击订单列表按钮
    clickBtnGroups(index, orderItem, id, ) {
        if (id == 'anotherOrder') {
            this.anotherOrder(orderItem.c_ord_no)
        } else if (id == 'confirmPayment') {
            this.confirmPayment(orderItem.c_ord_no)
        } else if (id == 'confirmReceipt') {
            this.confirmReceipt(orderItem.c_ord_no,() => {
                this.state.orderlist.map((item,i) => {
                    if(item.c_ord_no == orderItem.c_ord_no){
                        if(this.state.states == '0'){ //全部列表
                            item.ozt = '交易成功'
                            item.fhzt = '已签收'
                        }
                    }
                })
                if(this.state.states != '0'){ 
                    this.state.orderlist.splice(index,1)
                }
                this.setState({orderlist: this.state.orderlist})
            })
        } else if (id == 'cancelOrder') {
            this.cancelOrder(orderItem.c_ord_no,() => {
                this.state.orderlist.splice(index,1)
                this.setState({orderlist: this.state.orderlist})
            })
        } else if (id == 'afterSale' || id == 'evaluate') {  // 申请售后、去评价
            Taro.navigateTo({url: `/pages/${id}/${id}?orderItem=${JSON.stringify(orderItem)}`})
        }
    }
    // 再来一单
    anotherOrder(orderNo) {
        base.showLoading()
        let str = `orderNO`
        let params = {
            bNo: '415',
            orderNO: orderNo
        }
        api.get(str, params, (res) => {
            base.showModal(res.msg,false,() => {
                Taro.navigateTo({url: '/pages/shopcart/shopcart'})
            })
        },(err) => {
            console.log(err)
        },() => {
            Taro.hideLoading()
        })
    }
    // 确认付款
    confirmPayment(orderNo) {
        let userInfo = Taro.getStorageSync('userInfo')
        let str = `orderNO&mebno&ShopNo`
        let params = {
            bNo: 422,
            orderNO: orderNo,
            mebno: userInfo.C_MB_NO,
        }
        api.get(str, params, (res) => {
            console.log(res)
            common.payment(orderNo,() => { //支付成功 - 刷新页面
                this.setState({
                    orderlist: [],
                    pageindex: 1,
                    hasPgEnd: false,
                    showView: false
                }, () => {
                    base.showLoading()
                    this.getOrderList()
                })
            },() => { //取消支付
            },() => { //错误
            })
        },(err) => {
            base.showModal(err.msg)
        },() => {
            Taro.hideLoading()
        })
    }
    // 确认收货
    confirmReceipt(orderNo,calback) {
        base.showLoading()
        let str = `orderNO`
        let params = {
            bNo: '408',
            orderNO: orderNo,
        }
        api.get(str, params, (res) => {
            base.showToast(res.msg)
            if(calback){calback()}
        },(err) => {
            console.log(err)
        },() => {
            Taro.hideLoading()
        })
    }
    // 取消订单
    cancelOrder(orderNo,callback) {
        base.showLoading()
        let str = `ShopNo&mebNo&subOrderNo`
        // let params = {
        //     bNo: '406',
        //     orderNO: orderNo
        // }
        let params = {
            bNo: 'GO0103',
            ShopNo: 100233,
            mebNo: 1009047,
            subOrderNo: 'DS191105155110023300157'
        }
        api.get(str, params, (res) => {
            base.showToast(res.msg)
            if(callback){callback()}
        },(err) => {
            console.log(err)
        },() => {
            Taro.hideLoading()
        })
    }
    // 上拉加载
    onReachBottom(){
        if(this.state.hasPgEnd){return}
        base.showLoading()
        this.state.pageindex ++;
        this.getOrderList()
    }
    // 跳转订单详情
    navTo(orderId){
        console.log(orderId)
        Taro.navigateTo({
            url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
        })
    }
    render() {
        let {showView, orderlist} = this.state
        return (
            <View className='mainOrder'>
                <View className='tab-nav bg-white'>
                <TabBar states={this.state.states} onTabTap={this.tabTap.bind(this)}></TabBar>
                </View>
                {showView &&
                    <View className='order-list'>
                        {orderlist.length > 0 &&
                            <Block>
                                {orderlist.map((item,i) => {
                                    return (
                                        <View for={i} key={'order' + i} className='weui-cells'>
                                            <View className='weui-cell' onClick={this.navTo.bind(this,item.subOrderNo)}>
                                                <View className='weui-cell__bd'>
                                                    <View className='text-small'>{item.shopName}</View>
                                                    <View className='text-gray text-small'>订单编号：{item.subOrderNo}</View>
                                                </View>
                                                <View className='weui-cell__ft'>
                                                    <View className='text-main text-small'>{item.orderState ==1?'待付款':
                                                                                            (item.orderState === 3 ? '待发货':
                                                                                            (item.orderState === 4? '待收货':
                                                                                            (item.orderState === 5? '待自提':
                                                                                            (item.orderState === 20? '已完成':
                                                                                            (item.orderState === 100? '已取消':"状态异常")))))}
                                                    </View>
                                                    <View className='text-gray text-small'><Text>{item.orderTime}</Text> <Text>{item.ofz}</Text></View>
                                                </View>
                                            </View>
                                            {/* <View className='weui-cell weui-cell-p0' onClick={this.navTo.bind(this,item.mainOrderNo)}> */}
                                            <View className='weui-cell weui-cell-p0' >
                                                <View className='weui-cell__hd'>
                                                    <Goodlist glist={item.goodsList} domainImg={this.state.domainImg}></Goodlist>
                                                </View>
                                            </View>
                                            <View className='weui-cell'>
                                                <View className='weui-cell__bd'>
                                                    <View className='text-main'>合计：￥{item.totalMoney}</View>
                                                </View>
                                                <View className='weui-cell__ft'>
                                                {/* item.c_ord_no */}
                                                    <Btngroups ozt={item.orderState ==1?'待付款':
                                                                (item.orderState === 3 ? '待发货':
                                                                (item.orderState === 4? '待收货':
                                                                (item.orderState === 5? '待自提':
                                                                (item.orderState === 20? '已完成':
                                                                (item.orderState === 100? '已取消':"状态异常")))))} N_ISCOMMENT={item.commentState} onBtnGroups={this.clickBtnGroups.bind(this,i, item)}></Btngroups>
                                                </View>
                                            </View>
                                        </View> 
                                    )
                                })}
                                {this.state.hasPgEnd &&
                                    <View className='p20 ac'>没有更多数据了</View>
                                }
                            </Block>
                        }
                        {orderlist.length == 0 && <View className='empty-box'>您还没有相关订单</View>}
                    </View>
                }
            </View>
        )
    }
}

